package com.kds.changzhou.dao;

import com.kds.changzhou.data.Function;
import com.kds.changzhou.data.Gateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

@Repository
@Slf4j
public class ConfigDao {

    static final String sql = "SELECT building_config.buildingCode, data_mapping.gateway_id,data_mapping.meter_id,data_mapping.function_id, data_mapping.coding, data_mapping.source_fid FROM data_mapping INNER JOIN building_config ON data_mapping.building_code = building_config.buildingCode WHERE `disable` = 0   ORDER BY buildingCode, gateway_id,meter_id";

    @Autowired
    private JdbcTemplate template;


    public List<Gateway> queryGateways() {


        List<Gateway> gateways = new LinkedList<>();


        template.query(sql, new RowCallbackHandler() {

            private Gateway gateway = null;

            @Override
            public void processRow(ResultSet rs) throws SQLException {


                String buildingCode = rs.getString("buildingCode");

                String gateway_id = rs.getString("gateway_id");

                Function function = null;

                if (gateway == null) {
                    gateway = new Gateway(buildingCode, gateway_id);
                    gateways.add(gateway);
                } else {
                    if (gateway.getBuildingCode().equals(buildingCode) && gateway.getGatewayId().equals(gateway_id)) {

                        //当前处理的function result是在同一个gateway中
                    } else {
                        gateway = new Gateway(buildingCode, gateway_id);
                        gateways.add(gateway);
                    }
                }


                function = new Function();
                gateway.getFunctions().add(function);

                String meter_id = rs.getString("meter_id");
                function.setMeterid(meter_id);

                String function_id = rs.getString("function_id");
                function.setFunctionId(function_id);

                String coding = rs.getString("coding");
                function.setCoding(coding);

                String source_fid = rs.getString("source_fid");
                function.setExpression(source_fid);

            }
        });

        return gateways;
    }

}
